package cn.iocoder.yudao.module.system.service.info;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.system.controller.admin.info.vo.SystemInfoPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.info.vo.SystemInfoSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.info.SystemInfoDO;
import cn.iocoder.yudao.module.system.dal.mysql.info.SystemInfoMapper;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.INFO_NOT_EXISTS;

/**
 * 系统信息 Service 实现类
 *
 * @author admin
 */
@Service
@Validated
public class SystemInfoServiceImpl implements SystemInfoService {

    @Resource
    private SystemInfoMapper infoMapper;

    @Override
    public Long createInfo(SystemInfoSaveReqVO createReqVO) {
        // 插入
        SystemInfoDO info = BeanUtils.toBean(createReqVO, SystemInfoDO.class);
        if (info.getId() != null) {
            updateInfo(createReqVO);
            return info.getId();
        }
        infoMapper.insert(info);
        // 返回
        return info.getId();
    }

    @Override
    public void updateInfo(SystemInfoSaveReqVO updateReqVO) {
        // 校验存在
        validateInfoExists(updateReqVO.getId());
        // 更新
        SystemInfoDO updateObj = BeanUtils.toBean(updateReqVO, SystemInfoDO.class);
        infoMapper.updateById(updateObj);
    }

    @Override
    public void deleteInfo(Long id) {
        // 校验存在
        validateInfoExists(id);
        // 删除
        infoMapper.deleteById(id);
    }

    private void validateInfoExists(Long id) {
        if (infoMapper.selectById(id) == null) {
            throw exception(INFO_NOT_EXISTS);
        }
    }

    @Override
    public SystemInfoDO getInfo(Long id) {
        return infoMapper.selectById(id);
    }

    @Override
    public PageResult<SystemInfoDO> getInfoPage(SystemInfoPageReqVO pageReqVO) {
        return infoMapper.selectPage(pageReqVO);
    }

    @Override
    @Cacheable(cacheNames = "SYSTEM_INFO_DATA", key = "'INFO_DATA'", condition = "#result != null")
    public SystemInfoDO getInfo() {
        return infoMapper.selectList().get(0);
    }

}